package com.shushan.permission;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.permission.FloatPermissionUtil;
import com.android.permission.OpenAutoStartUtil;
import com.android.permission.rom.RomType;
import com.android.permission.rom.RomUtils;
import com.shushan.accessibility.AccessibilityOperator;
import com.shushan.accessibility.OpenAccessiSettingHelper;
import com.shushan.accessibility.PermissionOpenActivity;
import com.shushan.accessibility.emui.EmuiOperator;
import com.shushan.accessibility.funtouch.FuntouchOperator;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.receiver.LockAdminReceiver;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.util.OpenSettingUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToastUtils;

import static com.android.permission.rom.RomType.EMUI_ROM;

/**
 * @ClassName: PermissionAccessibilityActivity
 * @Desciption: 辅助功能权限主界面
 * @author: yichaohua
 * @date: 2018-07-03
 */
public class PermissionAccessibilityActivity extends Activity implements View.OnClickListener{

    private static final String TAG = "PermissionAccessibilityActivity";

    private RelativeLayout closeLockLayout;
    private RelativeLayout windowLayout;
    private RelativeLayout adminEnableLayout;

    private Button accessibilityButton;
    private Button completeButton;
    private Button windowButton;
    private Button closeLockButton;
    private Button adminEnableButton;
    private Button usageButton;
    private Button powerManagerButton;
    private Button finishButton;

    private ImageView accessibilityImg;
    private ImageView completedImg;
    private ImageView windowImg;
    private ImageView usageImg;
    private ImageView adminEnableImg;
    private ImageView closeLockImg;
    private ImageView closePowerImg;

    private boolean isAccessOpen = false;
    private boolean isOpenComplete = false;
    private boolean isOpneWindow = false;
    private boolean isColoseLock = false;
    private boolean isUsageable = false;
    private boolean isAdminEnable = true;
    private boolean isPowerClose = false;

    private RomType romType;
    private DevicePolicyManager dpm;
    private ComponentName adminComponent;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.permission_access_main_activity);

        dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
        adminComponent = new ComponentName(this, LockAdminReceiver.class);

        romType = RomUtils.getRomType(this);
        Log.i(TAG,"romType=" + romType.toString());

        initView(romType);

        initData(romType);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        isAccessOpen = intent.getBooleanExtra("isAccessOpen",false);
        boolean isAccessResult = intent.getBooleanExtra("isAccessResult",false);
        Log.i(TAG,"isAccessOpen=" + isAccessOpen + " isAccessResult=" + isAccessResult);

        if(isAccessOpen){
            accessibilityButton.setOnClickListener(null);
            accessibilityImg.setVisibility(View.VISIBLE);

            Intent intent1 = new Intent(this,PermissionOpenActivity.class);
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent1.putExtra("openIndex",1);
            startActivity(intent1);
        }else if (isAccessResult){
            boolean result = intent.getBooleanExtra("result",false);
            int resultCode = intent.getIntExtra("resultCode",0);
            Log.i(TAG,"resultCode=" + resultCode + " result=" + result);

//            onAutoResult(result,resultCode);
        }

        setIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView(RomType romType) {
        accessibilityButton = findViewById(R.id.permission_main_accessibility_btn);
        accessibilityButton.setOnClickListener(this);
        accessibilityImg = findViewById(R.id.permission_main_accessibility_img);
        usageButton = findViewById(R.id.permission_main_usage_btn);
        usageButton.setOnClickListener(this);
        usageImg = findViewById(R.id.permission_main_usage_img);
        adminEnableButton = findViewById(R.id.permission_main_admin_enable_btn);
        adminEnableButton.setOnClickListener(this);
        adminEnableImg = findViewById(R.id.permission_main_admin_enable_img);
        powerManagerButton = findViewById(R.id.permission_main_power_manager_btn);
        powerManagerButton.setOnClickListener(this);
        closePowerImg = findViewById(R.id.permission_main_power_manager_img);
        windowLayout = findViewById(R.id.permission_main_open_window_layout);
        completedImg = findViewById(R.id.permission_main_open_completed_img);
        windowImg = findViewById(R.id.permission_main_open_window_img);
        closeLockImg = findViewById(R.id.permission_main_close_lock_img);
        closeLockLayout = findViewById(R.id.permission_main_close_lock_layout);
        completeButton = findViewById(R.id.permission_main_open_completed_btn);
        completeButton.setOnClickListener(this);
        windowButton = findViewById(R.id.permission_main_open_window_btn);
        windowButton.setOnClickListener(this);
        closeLockButton = findViewById(R.id.permission_main_close_lock_btn);
        closeLockButton.setOnClickListener(this);
        finishButton = findViewById(R.id.permission_main_finish_btn);
        finishButton.setOnClickListener(this);

        if(romType == EMUI_ROM  && RomUtils.getEmuiLeval(this) >= 14){
            completeButton.setVisibility(View.GONE);
            completedImg.setVisibility(View.GONE);
            isOpenComplete = true;
        }
    }

    private void initData(RomType romType) {
        if(romType == RomType.SMARTISAN_ROM){
            powerManagerButton.setText("开启后台常驻");
        }

        if(romType == RomType.SAMSUNG_ROM || romType == RomType.FLYME_ROM){
            isPowerClose = true;
            powerManagerButton.setVisibility(View.GONE);
            closePowerImg.setVisibility(View.GONE);
        }

        if(!(romType == RomType.FUNTOUCHOS_ROM || romType == RomType.SMARTISAN_ROM)){
            if(FloatPermissionUtil.checkPermission(this)){
                isOpneWindow = true;
                windowImg.setVisibility(View.VISIBLE);
                windowButton.setOnClickListener(null);
            }else {
                isOpneWindow = false;
                windowImg.setVisibility(View.GONE);
                windowButton.setOnClickListener(this);
            }
        }

        if (dpm.isAdminActive(adminComponent)) {
            isAdminEnable = true;
            adminEnableImg.setVisibility(View.VISIBLE);
            adminEnableButton.setOnClickListener(null);
        } else {
            isAdminEnable = false;
            adminEnableImg.setVisibility(View.GONE);
            adminEnableButton.setOnClickListener(this);
        }

        KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        if(!mKeyguardManager.isKeyguardSecure()){
            isColoseLock = true;
            closeLockImg.setVisibility(View.VISIBLE);
            closeLockButton.setOnClickListener(null);
            closeLockLayout.setVisibility(View.GONE);
        }else {
            isColoseLock = false;
            closeLockImg.setVisibility(View.GONE);
            closeLockButton.setOnClickListener(this);
            closeLockLayout.setVisibility(View.VISIBLE);
        }

        if(SystemUtils.checkUsagePermission(this)){
            isUsageable = true;
            usageImg.setVisibility(View.VISIBLE);
            usageButton.setOnClickListener(null);
        }else {
            isUsageable = false;
            usageImg.setVisibility(View.GONE);
            usageButton.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.permission_main_accessibility_btn:
                OpenAccessiSettingHelper.jumpToSettingPage(this);
                break;
            case R.id.permission_main_power_manager_btn:
                startActivityForResult(new Intent(this,PowerManagerActivity.class),100);
                break;
            case R.id.permission_main_open_completed_btn:
                startActivityForResult(new Intent(this,OpenCompleteActivity.class),100);
                break;
            case R.id.permission_main_open_window_btn:
                startActivityForResult(new Intent(this,OpenWindowActivity.class),100);
                break;
            case R.id.permission_main_usage_btn:
                startActivityForResult(new Intent(this,OpenUsageActivity.class),100);
                break;
            case R.id.permission_main_admin_enable_btn:
                checkAndEnableAdmin();
                break;
            default:
                break;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.i(TAG,"onActivityResult requestCode=" + requestCode + " resultCode=" + resultCode);

        if(requestCode == 150){
            if (dpm.isAdminActive(adminComponent)) {
                isAdminEnable = true;
                adminEnableImg.setVisibility(View.VISIBLE);
            }
        }else{
            if(resultCode == 200){
                isOpenComplete = true;
                completedImg.setVisibility(View.VISIBLE);
            }else if(resultCode == 300){
                RomType romType = RomUtils.getRomType(this);
                if(!(romType == RomType.FUNTOUCHOS_ROM || romType == RomType.SMARTISAN_ROM)){
                    if(FloatPermissionUtil.checkPermission(this)){
                        isOpneWindow = true;
                        windowImg.setVisibility(View.VISIBLE);
                    }else {
                        isOpneWindow = false;
                        windowImg.setVisibility(View.GONE);
                    }
                }else {
                    isOpneWindow = true;
                    windowImg.setVisibility(View.VISIBLE);
                }

            }else if(resultCode == 400){
                KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
                if(!mKeyguardManager.isKeyguardSecure()){
                    isColoseLock = true;
                    closeLockImg.setVisibility(View.VISIBLE);
                }else {
                    isColoseLock = false;
                    closeLockImg.setVisibility(View.GONE);
                }
            }else if(resultCode == 500){
                isPowerClose = true;
                closePowerImg.setVisibility(View.VISIBLE);
            }else if(resultCode == 600){
                if(SystemUtils.checkUsagePermission(this)){
                    isUsageable = true;
                    usageImg.setVisibility(View.VISIBLE);
                }else {
                    isUsageable = false;
                    usageImg.setVisibility(View.GONE);
                }
            }
        }
    }

    private void onResult(int resultCode) {
        if(resultCode == 200){
            isOpenComplete = true;
            completedImg.setVisibility(View.VISIBLE);
            completeButton.setOnClickListener(null);
        }else if(resultCode == 300){
            isOpneWindow = true;
            windowImg.setVisibility(View.VISIBLE);
            windowButton.setOnClickListener(null);
        }else if(resultCode == 400){
            if (dpm.isAdminActive(adminComponent)) {
                isAdminEnable = true;
                adminEnableImg.setVisibility(View.VISIBLE);
                adminEnableButton.setOnClickListener(null);
            }
        } else if(resultCode == 500){
            isPowerClose = true;
            closePowerImg.setVisibility(View.VISIBLE);
            powerManagerButton.setOnClickListener(null);
        }else if(resultCode == 600){
            if(SystemUtils.checkUsagePermission(this)){
                isUsageable = true;
                usageImg.setVisibility(View.VISIBLE);
                usageButton.setOnClickListener(null);
            }else {
                isUsageable = false;
                usageImg.setVisibility(View.GONE);
                usageButton.setOnClickListener(this);
            }
        }

    }

    private void onAutoResult(boolean result,int resultCode) {
        if(result){
            onResult(resultCode);
        }

        switch (resultCode){
            case 200:
                Intent intent2 = new Intent(this,PermissionOpenActivity.class);
                intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent2.putExtra("openIndex",3);
                startActivity(intent2);
                break;
            case 300:
                Intent intent4 = new Intent(this,PermissionOpenActivity.class);
                intent4.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent4.putExtra("openIndex",5);
                startActivity(intent4);
                break;
            case 400:
                Intent intent3 = new Intent(this,PermissionOpenActivity.class);
                intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent3.putExtra("openIndex",4);
                startActivity(intent3);
                break;
            case 500:
                Intent intent1 = new Intent(this,PermissionOpenActivity.class);
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent1.putExtra("openIndex",2);
                startActivity(intent1);
                break;
            case 600:
                break;
            default:
                break;
        }
    }

    private boolean checkAndEnableAdmin() {
        boolean enableAdmin = false;
        if (!dpm.isAdminActive(adminComponent)) {
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminComponent);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, this.getString(R.string.device_admin_hint));
            startActivityForResult(intent, 150);
            enableAdmin = false;
        } else {
            Log.i(TAG,"设备管理器已激活");
            enableAdmin = true;
        }

        return enableAdmin;
    }

}
